<?php
namespace app\index\controller;

use think\Request;
use think\Db;

class Cart extends Common
{   
    public function _initialize()
    {
        parent::_initialize();
    }
    
    public function index()
    {	
    	// $where['a.uid'] = UID;
    	// $list = DB::name('cart')
    	// 	->field('a.num as num, b.*')
    	// 	->alias('a')
	// 	->join('__GOODS__ b', 'b.id=a.gId', 'LEFT')
    	// 	->where($where)
    	// 	->order('b.status desc, b.id asc')
    	// 	->select();
    	// $this->assign('list', $list);
    	return $this->fetch();
    }

    /**
     * 添加商品到购物车
     * @param int $gId 商品id
     * @param int $num 商品数量
     */
    public function add($gId, $num) {
        $data['uid'] = UID;
        $data['gId'] = $gId;

        $res = DB::name('cart')->where($data)->limit('1')->select();
        // 存在则更新，不存在则插入
        if($res) {
            $data['num'] = $num;
            $resNum = DB::name('cart')->insert($data);
        } else {
            $resNum = DB::name('cart')->where('id', $gId)->setInc('num', $num);
        }
        if($resNum == 1) {
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }

    /**
     * 删除单条购物车记录
     */
    public function delete()
    {
    	$gId = input('post.id');
    	$result = DB::name('cart')
		    		->where('uid', UID)
		    		->where('gId', $gId)
		    		->delete();
		if($result != 0) {
			return $this->success('删除成功！');
		} else {
			return $this->error('删除失败！');
		}
    }

    /**
     * 删除多条购物车记录
     */
    public function deleteAll()
    {   
    	$gIds = input('post.ids');
    	if(empty($gIds)) {
			return $this->error('请选择商品！');
		}
  //   	$result = DB::name('cart')
  //   				->where('uid', UID)
  //   				->where('gId', 'in' ,$gIds)
  //   				->delete();
  //   	if($result != false) {
		// 	return $this->success('删除成功！');
		// } else {
		// 	return $this->error('删除失败！');
		// }
    }

    /**
     * ajax更改商品数量
     */
    public function changeNum()
    {   
        if (Request::instance()->isPost()) {
            $gId = input('post.gId');
            $num = input('post.num');

            $where['uid'] = UID;
            $where['gId'] = $gId;

            $resNum = DB::name('cart')->where($where)->setInc('num', $num);
            if ($resNum != 0) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
    }
}
